<template>
  <el-row>
    <el-col :span="24"> 
      <el-table
        stripe
        :data="props.info.columns"
        :border="true"
        :cell-style="cellStyle"
         :header-cell-class-name="'box-item-tip'"
        :header-cell-style="({ row, column, rowIndex, columnIndex }) => { return headerCellStyle({ row, column, rowIndex, columnIndex, list: props.info.columns }) }"
        @header-click="onHeaderClick">
        <template v-for="(column, index) in props.info.headers" :key="index">
          <el-table-column :prop="`p${index}`" :label="column[`p${index}`]" minWidth="120" v-if="index ==0" width="100">
            <template #default="scope">
              <div style="text-align:center">
                  <span v-if="getFilterNames(scope.row, `p${index}`)=='ETA' || getFilterNames(scope.row, `p${index}`)=='ATA' " style=" font-style: italic">{{ getFilterNames(scope.row, `p${index}`) }}</span>
                  <span v-else>{{ getFilterNames(scope.row, `p${index}`) }}</span>
              </div>			  
            </template>
          </el-table-column>
          <el-table-column :prop="`p${index}`" minWidth="120" v-else >
            <template #header="scope">
              <div style="text-align:center;position: relative;" >
                <span>{{column[`p${index}`]}} </span>
                <el-tooltip v-if="props.info.details[index-1].changeHistory" :offset="0" effect="light"
                 placement="right">
                  <template #content="scope"> 
                    <div v-html='props.info.details[index-1].changeHistory.replace("\\r\\n","<br/>")'></div> 
                  </template>
                  <el-icon  class="box-item">
                    <WarningFilled />
                  </el-icon>
                </el-tooltip> 
              </div>
            </template>
            <template #default="scope">
			        <div style="text-align:center;word-break: break-all !important;white-space:normal!important;  word-wrap: break-word;" v-html="getFilterNames2(scope.row, `p${index}`)">
			        </div>
            </template> 
          </el-table-column>
        </template>
      </el-table>
      <!-- </el-card> -->
      <pagination v-show="total > 0" :total="total" :page="queryParams.pageNum" :limit="queryParams.pageSize"
        @pagination="pageQuery" style="float: right" />
    </el-col>
  </el-row>

  <el-dialog destroy-on-close draggable :width="1280" :title="dialogTitle" v-model="dialogFormVisible" append-to-body>
    <el-form :model="formParam" :rules="rules" ref="custForm">
      <el-row>
        <el-col :span="8">
          <el-form-item label="Vessel Name" label-width="120px" prop="vesselName" required>
            <el-select v-model="formParam.vesselName" filterable placeholder="choose Vessel" @change="selectVoyage">
              <el-option :key="item.vesselName" :label="item.vesselName" :value="item.vesselName"
                v-for="item in vessels">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="Voyage Code" label-width="120px" prop="voyageNo" required>
            <el-input type="number" readonly v-model="formParam.voyageNo" ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="status" label-width="120px" prop="status" required>
            <el-select v-model="formParam.status">
              <el-option :key="index" :label="item" :value="index" v-for="(item, index) in statuss" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{
          $t("ship.button.cancel")
          }}</el-button>
        <el-button type="primary" @click="submitForm">{{
          $t("ship.button.submit")
          }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
  // @ts-nocheck
  import { ref, onMounted, computed, reactive, nextTick, defineEmits } from "vue";
  import service from "@/utils/request";
  import { ElNotification, ElMessageBox } from "element-plus";
  const props = defineProps({
    info: {
      type: Object,
      default: () => {},
    }
  })

  const emit = defineEmits(['click-port-name'])

  const onHeaderClick = (column) => {
    if (column.no > 0) {
      emit('click-port-name', {
        row: props.info,
        titleValue: props.info.headers[column.no][column.property],
        id: props.info.details[column.no - 1].id
      })
    }
  }

 
  const cellStyle = ({ row, column, rowIndex, columnIndex }) => {
    return {}
  }

  const titleStyle = {
    color: '#fff',
    fontWeight: 'bold',
    fontSize: '12px'
  }

  const headerCellStyle = ({ row, column, rowIndex, columnIndex, list }) => {
    const index = list.findIndex(item => item.p0 === 'ACTIVITY')
    const hasColor = index >= 0 && column.label !== 'ROTATION' && list[index][column.property] && columnIndex > 0
    if (hasColor) {
      if (list[index][column.property].includes(0) && list[index][column.property].includes(1)) {
        return {
          backgroundColor: 'rgb(230, 162, 60)',
          ...titleStyle
        }
      }
      if (list[index][column.property].includes(0)) {
        return {
          backgroundColor: 'rgb(64, 158, 255)',
          ...titleStyle
        }
      }
      if (list[index][column.property].includes(1)) {
        return {
          backgroundColor: 'rgb(245, 108, 108',
          ...titleStyle
        }
      }
    }
  }

  // 格式化名称
    const getFilterNames2 = (row, field) => {
    // 状态栏 && 非第一栏
    if (row.p0 === 'ACTIVITY' && field !== 'p0') {
      let names = [];
      (row[field] || []).map((item) => {
        if (item === 0) {
          names.push('LOADING')
        }
        if (item === 1) {
          names.push('DISCHARGING')
        }
        if (item === 2) {
          names.push('BUNKERING')
        }
        if (item === 3) {
          names.push('D/D or SURVEY')
        }
        if(item === 4){
          names.push('CREW CHANGE')
        }
        if(item === 5){
          names.push('PASSING')
        }
      })
      return names.join(' <br/> ')
    }
    return row[field] || '';
  }
  const getFilterNames = (row, field) => {
    // 状态栏 && 非第一栏
    if (row.p0 === 'ACTIVITY' && field !== 'p0') {
      let names = [];
      (row[field] || []).map((item) => {
        if (item === 0) {
          names.push('LOADING')
        }
        if (item === 1) {
          names.push('DISCHARGING')
        }
        if (item === 2) {
          names.push('BUNKERING')
        }
        if (item === 3) {
          names.push('D/D or SURVEY')
        }
        if(item === 4){
          names.push('CREW CHANGE')
        }
         if(item === 5){
          names.push('PASSING')
        }
      })
      return names.join(' / ')
    }
    return row[field] || '';
  }

  let vessels = ref([] as any);
  const custForm = ref(null);
  const formRef = ref()
  const dialogTitle = ref("");
  const initForm = {
    scheduleId: null,
    voyageId: null,
    vesselName: null,
    voyageNo: null,
    details: [],
    status: 0,
  };
  const formParam = reactive(Object.assign({}, initForm));

  let ports = ref([] as any);
  const activitys = ["LOADING", "DISCHARGING", "BUNKERING", "D/D or SURVEY","CREW CHANGE","PASSING"]
  const total = ref(0);

  const queryParams = reactive({
    pageNum: 1,
    pageSize: 20,
    voyageNo: null,
    vesselName: null,
    orderByColumn: undefined,
    isAsc: undefined,
  });

  const statuss = ["Active", "Cancelled", "Closed"] as any;

  const listData = ref([]);


  let formObj = ref({
    recordData: [{
      seqNo: 1,
      portName: null,
      eta: null,
      acta: null
    }

    ]
  })

  // 表格验证
  const rules = ref({
    defultRule: [
      {
        required: true,
        message: 'Mandatory Field'
      }
    ],
    portRule: [
      {
        required: true,
        message: 'Mandatory Field'
      },
      {
        validator: (rule, value, callback) => { 
            callback(); 
        }
      }
    ],
    etRule: [
      {
        required: true,
        message: 'Mandatory Field'
      },
      {
        validator: (rule, value, callback) => { 
          callback();
        }
      }
    ],
    atRule: [
      {
        required: false,
        message: 'Mandatory Field'
      },
      {
        validator: (rule, value, callback) => { 
          callback();
        }
      }
    ]
  });

  const onFormValid = () => {
    nextTick(() => {
      formRef.value.validate()
    })
  }


  const dialogFormVisible = ref(false);

  let isAdd = false;

  const addClickEvent = () => {
    dialogTitle.value = "Create Schedule";
    isAdd = true;
    dialogFormVisible.value = true;
    Object.assign(formParam, initForm);

    formObj.value.recordData = [
      {
        seqNo: 1,
        portName: null,
        eta: null,
        acta: null
      },
      {
        seqNo: 2,
        portName: null,
        eta: null,
        acta: null
      }
    ]
  };

  const resetForm = () => {
    // @ts-ignore
    custForm.value.resetFields();
  };

  const submitForm = () => {
    // @ts-ignore
    custForm.value.validate(async (valid) => {
      if (!valid) {
        // @ts-ignore
        ElNotification.warning({
          title: "Prompt information",
          message: "verification not success！",
          position: "bottom-right",
        });
        return;
      }
      // @ts-ignore
      formRef.value.validate(async (valid) => {
        if (!valid) {
          // @ts-ignore
          ElNotification.warning({
            title: "Prompt information",
            message: "verification not success！",
            position: "bottom-right"
          });
          return;
        }

        if (formObj.value.recordData.length === 0) {
          ElNotification.warning({
            title: "Prompt information",
            message: "data must input！",
            position: "bottom-right"
          });
          return;
        }

        formParam.details = formObj.value.recordData; 
        await service[isAdd ? "post" : "put"]("shipping/schedule", formParam);
        // @ts-ignore
        ElNotification.success({
          title: "Prompt information",
          message: "save successful!",
          position: "bottom-right",
        });
        dialogFormVisible.value = false;
        refreshTable();
      })
    })
  };

  const pageQuery = async (e) => {
    queryParams.pageNum = e.page;
    queryParams.pageSize = e.limit;
    refreshTable();
  };

  const search = () => {
    refreshTable();
  };


  const handleSortChange = async (column: any) => {
    queryParams.orderByColumn = column.prop;
    queryParams.isAsc = column.order; //动态取值排序顺序
    refreshTable();
  };

  // props.info.headers = props.info.headers.map((item, index ) => {
  //       return { [`p${index}`]: item }
  // })
  // props.info.columns = props.info.columns.map((item, index) => {
  //       const obj = {}
  //       item.map((subItem, sindex) => {
  //         obj[`p${sindex}`] = subItem
  //       })
  //       return obj
  //     })
</script>

<style lang="scss" scoped>

  ::v-deep(.el-table__header) {
    line-height: 48px !important;
    height: 48px;
  }

  .header-wrapper {
    border: 1px solid #ebeef5;
    border-bottom: none;
    padding: 10px;
  }

  .daf-table {
    margin: 0;
    padding: 0;
  }

  .tips {
    text-align: right;

    .el-button {
      margin-left: 10px;
      margin-right: 15px;
    }
  } 
  .el-table .cell {
	  text-align:center !important;
		color: #888 !important;
    overflow: auto !important;
	}

  .box-item{
    position: absolute;
    size:14px;
    top: -5px;
    right: -4px;
    z-index: 999;
  }
  ::v-deep(.cell){
    overflow:visible !important;
  }
</style>